package dnl.util.ui.actions;

import java.util.HashMap;
import java.util.Iterator;

import javax.swing.Action;
import javax.swing.JMenu;
import javax.swing.JMenuItem;

/**
  * Groups a collection of related actions.<br>
  * 
  * 
  * @author Daniel Or
  * @version 1.0
  */
public class ActionGroup {

	/**
	 * 
	 * @param name
	 */
	public ActionGroup(String name){
		this.name = name;
		this.jmenu = new JMenu(name);
		actions = new HashMap<String, Action>();
	}

	/**
	 * 
	 * @param name
	 * @param actions
	 */
	public ActionGroup(String name, HashMap<String, Action> actions){
		this.name = name;
		this.jmenu = new JMenu(name);
		this.actions = actions;
	}

	/**
	 * Adds a <code>JSeparator</code> to the end of this group menu and then
	 * adds all the items in <code>aGroup</code>.<br>
	 * Note that setEnabled() of this group has no effect on the added group.
	 * @param aGroup
	 */
	public void addToMenu(ActionGroup aGroup){
		jmenu.addSeparator();
		JMenuItem[] nItems = aGroup.getItems();
		for (int i = 0; i < nItems.length; i++) {
			jmenu.add(nItems[i]);
		}
	}
	
	/**
	 * 
	 * @param aGroup
	 */
	public void addAsSubMenu(ActionGroup aGroup){
		jmenu.add(aGroup.getMenu());
	}

	/**
	 * Adds a <code>com.blz.gui.actions.AbstractAction</code> to the actions
	 * that are reffered by this <code>ActionGroup</code>.
	 * @param action
	 */
	public void addAction(AbstractAction action){
		if(action == null)
			return;
		addAction(action, action.getName());
	}

	/**
	 * 
	 * @param action
	 * @param actionName
	 */
	public void addAction(Action action, String actionName){
		actions.put(actionName, action);
		JMenuItem newItem = new JMenuItem(action);
		items.put(actionName, newItem);
		jmenu.add(action);
	}

	/**
	 * 
	 * @param actionName
	 * @return Action
	 */
	public Action getAction(String actionName){
		return actions.get(actionName);
	}
	
	/**
	 * 
	 * @return JMenu
	 */
	public JMenu getMenu(){
		return jmenu;
	}
	
	/**
	 * 
	 * @return JMenuItem[]
	 */
	public JMenuItem[] getItems(){	
		return items.values().toArray(new JMenuItem[]{});	
	}
	
	/**
	 * 
	 * @param enable
	 */
	public void setEnabled(boolean enable){
		for (Iterator<JMenuItem> iter = items.values().iterator(); iter.hasNext();) {
			JMenuItem element = iter.next();
			element.setEnabled(enable);
		}
	}
	
	/**
	 * 
	 * @param name
	 * @param enable
	 */
	public void setItemEnabled(String name, boolean enable){
		JMenuItem item = getMenuItem(name);
		if(item != null){
			item.setEnabled(enable);
		}
		else
			System.err.println("setItemEnabled()-- NULL");
	}
	
	/**
	 * 
	 * @param name
	 * @return JMenuItem
	 */
	public JMenuItem getMenuItem(String name){
		return  items.get(name);
	}

	String name;
	protected HashMap<String, Action> actions;
	protected HashMap<String, JMenuItem> items = new HashMap<String, JMenuItem>();
	JMenu jmenu;
}
